import { useModel } from '@umijs/max';
import type { UploadFile } from 'antd';
import { Upload } from 'antd';
import React, { useEffect, useState } from 'react';

type UploadFileTemplateProps = {
  [key: string]: any;
  accept?: string;
  maxCount?: number;
  children?: React.ReactNode;
  onChange?: (file: any) => void;
  showUploadList?: any;
  listType?: any;
  fileList?: any;
  disabled?: boolean;
  multiple?: boolean;
  beforeUpload?: (file: any, fileList: any) => any;
  directory?: boolean;
  className?: any;
  onUploadChange?: (val: boolean) => void;
};

export default function UploadFileTemplate(props: UploadFileTemplateProps) {
  const {
    accept,
    maxCount = 1,
    children,
    onChange,
    showUploadList = true,
    listType,
    fileList,
    disabled,
    multiple = false,
    beforeUpload,
    directory = false,
    className,
    onUploadChange,
    ...other
  } = props;
  const { initialState } = useModel('@@initialState');
  const [currentFileList, setCurrentFileList] = useState<UploadFile[]>([]);

  // 默认的 beforeUpload 实现
  const defaultBeforeUpload = (): boolean => {
    return true; // 默认允许上传
  };

  const handleChange = (info: { fileList: UploadFile[]; file: UploadFile }) => {
    const updatedFileList = info.fileList.map((file) => {
      if (file.uid === info.file.uid) {
        return {
          ...file,
          status: info.file.status,
          response: info.file.response,
        };
      }
      return file;
    });
    setCurrentFileList(updatedFileList);
    const hasUploading = info.fileList.every(
      (file) => file.status === 'done' || file.status === undefined,
    );
    if (onUploadChange) {
      onUploadChange(!hasUploading);
    }
    if (hasUploading && onChange) {
      onChange(info.fileList);
    }
  };

  // 图片预览
  const handlePreview = async (file: any) => {
    let src: any = file?.url || file?.originFileObj?.url;
    if (!src) {
      src = await new Promise<string>((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as Blob);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };

  useEffect(() => {
    // 编辑回显再操作没有status会有问题
    setCurrentFileList(
      fileList?.map((item: any, index: number) => {
        return {
          uid: `-1_${index}`, // 这里使用负数，避免与内部 ID 冲突
          name: item?.split('/')?.pop(),
          status: 'done',
          response: { url: item },
          thumbUrl: item,
        };
      }) || [],
    );
  }, [fileList]);

  return (
    <Upload
      className={className}
      disabled={disabled}
      fileList={currentFileList}
      listType={listType}
      accept={accept || 'image/*'}
      action="/api/herd/upload/oracle"
      maxCount={maxCount}
      data={{ userId: initialState?.user?.id || 'guest' }}
      onChange={handleChange}
      showUploadList={showUploadList}
      multiple={multiple}
      beforeUpload={beforeUpload ?? defaultBeforeUpload}
      directory={directory}
      onPreview={handlePreview}
      {...other}
    >
      {currentFileList?.length >= maxCount ? null : children}
    </Upload>
  );
}
